﻿// --------------------------------------------------------------------------------------------------------------------
// <copyright file="SubjectRepository.cs" company="">
//   Copyright (c) 2010/2011 All Right Reserved
// </copyright>
// <summary>
//   Contains SubjectRepository class declaration.
// </summary>
// --------------------------------------------------------------------------------------------------------------------

using EntityFrameworkExtensions;

namespace iBuproModel.Repositories.Classes
{
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;

    using iBuproModel.Repositories.Interfaces;

    /// <summary>
    /// Implements ISubjectRepository interface using linq to entities.
    /// </summary>
    public class SubjectRepository : GenericRepository<Subject>, ISubjectRepository
    {
        public new void Update(Subject subject)
        {
            if (context.Subjects.FirstOrDefault(p => p.Id == subject.Id) != null)
            {
                context.AttachTo(context.Subjects.EntitySet.Name, subject);
                context.SaveChanges();
            }
            else throw new Exception("Updated studentplan doesn't exists");
        }

        public IEnumerable<Subject> GetSubjectsForLector(User lector)
        {
            IUserRepository users = repositoryService.UserRepositoryCreateInstance();

            if (users.IsUserInRole(lector, "Lector") == false)
            {
                throw new Exception("User" + lector.Username + "is not in Lector role");
            }

            return lector.LectorSubjects.ToList();
        }

        public void UpdateLectorSubjectList(User lector, IEnumerable<int> ids)
        {
            ISubjectRepository subjects = repositoryService.SubjectRepositoryCreateInstace();

            lector.LectorSubjects.Clear();

            foreach (int id in ids)
            {
                lector.LectorSubjects.Add(subjects.First(s => s.Id == id));
            }
        }


        /*Rewrites base method. New method selects only visible members. This is because of deleting*/
        new public IQueryable<Subject> GetAll()
        {
            return context.CreateObjectSet<Subject>().OfTypeOnly<Subject>().Where(f => f.Visible == true);
        }


        public void Hide(int id)
        {
            Subject pom = this.First(s => s.Id == id);
            pom.Visible = false;
            this.SaveChanges();

        }
    }
}
